/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.collector;

import flexjson.JSONException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import za.org.foobar.famon.dto.CFailureBatch;
import za.org.foobar.famon.util.Util;
import za.org.foobar.famon.webapp.UserLogic;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPInputStream;

/**
 *
 */
public class FamonCollectorServlet extends HttpServlet {
    private final Log log = LogFactory.getLog(getClass());

    public FamonCollectorServlet() {
        log.debug("Creating FamonCollectorServlet");
    }

    public void service(HttpServletRequest request, HttpServletResponse servletResponse) throws ServletException, IOException {
        log.info("Got request from " + request.getRemoteHost() + "(" + request.getRemoteAddr() + "):" +
                request.getRemotePort());

        String contentCoding = request.getHeader("Content-Coding");
        log.info("ContentCode: " + contentCoding);
        String json;
        try {
            long t = System.currentTimeMillis();
            if ("gzip".equalsIgnoreCase(contentCoding)) {
                json = Util.readFile(new GZIPInputStream(request.getInputStream()));
            } else {
                json = Util.readFile(request.getInputStream());
            }
            t = System.currentTimeMillis() - t;
            log.info("Took " + t + " ms to get " + json.length() + " bytes of data");
        } catch (IOException e) {
            setResponseError(servletResponse, e, "INPUT");
            return;
        }
        if (log.isTraceEnabled()) {
            log.trace("Request JSON: \n" + json);
        }

        if (json.length() == 0) {
            //noinspection ThrowableInstanceNeverThrown
            setResponseError(servletResponse, new Exception("Empty JSON string"), "PARSE");
        }

        int i = json.indexOf(CFailureBatch.FAMON_PROTOCOL_VERSION_SEPARATOR);
        if (i < 0) {
            log.error("Could not find protocol version");
            if (log.isTraceEnabled()) {
                log.trace(json);
            }
            return;
        }
        String protocolVersion = json.substring(0, i);
        if (!isVersionSupported(protocolVersion)) {
            log.error("Un-compatible protocol version: " + protocolVersion);
            return;
        }
        if (json.length() > i+1) {
            json = json.substring(i+1);
        } else {
            log.error("Received blank JSON: " + json);
            return;
        }

        try {
            UserLogic.get().setSystemUser(true);
            FamonCollectorLogic.get().handleRequest(request, json);
        } catch (JSONException e) {
            setResponseError(servletResponse, e, "PARSE");
        } finally {
            UserLogic.get().setSystemUser(false);
        }
    }

    private void setResponseError(ServletResponse response, Throwable e, String errorCode) {
        log.error("ERR " + errorCode + "\n" +
                "Exception: " + e.getMessage() + "\n" +
                Util.exceptionStackTraceToString(e));

        // Give the user a meaningful error
        try {
            PrintWriter out = new PrintWriter(response.getOutputStream());
            out.println("ERR " + errorCode + " " + e.getMessage());
        } catch (IOException e2) {
            log.error("Could not write to response output stream: " + e2.getMessage() + "\n" +
                    Util.exceptionStackTraceToString(e2));
        }
    }

    private boolean isVersionSupported(String protocolVersion) {
        if (CFailureBatch.FAMON_PROTOCOL_VERSION.equals(protocolVersion)) {
            return true;
        }
        String currentVersions[] = CFailureBatch.FAMON_PROTOCOL_VERSION.split("[\\.]");
        String protocolVersions[] = protocolVersion.split("[\\.]");
        int len = Math.max(currentVersions.length, protocolVersion.length());
        for (int i = 0; i < len; i++) {
            int a, b;
            a = i < currentVersions.length ? Integer.parseInt(currentVersions[i]) : 0;
            b = i < protocolVersions.length ? Integer.parseInt(protocolVersions[i]) : 0;
            // If the digit is higher than the server's its a future version.
            // Also, the major version number MUST be the same.
            if (a < b || (i == 0 && a > b)) {
                return false;
            // If the digit is lower, the rest doesn't matter.
            } else if (a > b) {
                return true;
            }
        }
        return true;
    }
}
